#!/usr/local/bin/python2.7

import  os, copy
from constants import *

class Writer(object):
    """
    Used to write a plant component xml element to the specified directory
    path.  The filename is generated automatically from the Element
    tags/field data.
    """

    def __init__(self):
        """
        *component* is the xml.etree element to be written to file.  It can
        either be specified now during initialization or later by directly
        setting the instance attribute.
        """

        self._extension = 'none'
        self._dst_dir = Constants.parsed_files_dir
        self._component = None
        self._dst = None
        self.overwrite = False

    def saveFile(self):
        """
        Saves the plant component with its xml.etree element into a
        nicely formatted xml file.
        """

        self._validateThisWrite()
        self._buildDst()
        self._writeIt()

    def _writeIt(self):
        # overwritten by different types of writer subclasses
        pass

    def _validateThisWrite(self):
        """
        Make sure that the write is ready to proceed.  Otherwise, raise
        an exception.
        """

        if not os.path.exists(self._dst_dir):
            os.makedirs(self._dst_dir)

    def _buildDst(self):
        # add counter to end of filename if it already exists
        root_name = self._component.name
        name = root_name + '.' + self._extension

        count = 2
        if not self.overwrite:
            if os.path.isfile(os.path.join(self._dst_dir, name)):
                while True:
                    name = root_name + '_' + str(count) +'.'+self._extension
                    if not os.path.isfile(os.path.join(self._dst_dir,name)):
                        break
                    count += 1

        self._dst = os.path.join(self._dst_dir, name)

    def getDstDir(self):
        return self._dst_dir
    def setDstDir(self, val):
        self._dst_dir = val
    dst_dir = property(getDstDir, setDstDir)

    def getDst(self):
        return self._dst
    dst = property(getDst)

    def getComp(self):
        return self._component
    def setComp(self, val):
        self._component = copy.deepcopy(val)
    component = property(getComp, setComp)

